<template>
  <div class="grade-analysis">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>成绩分析</span>
          <el-button @click="handleBack">返回</el-button>
        </div>
      </template>

      <!-- 筛选条件 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="考试名称">
          <el-select
            v-model="searchForm.examId"
            placeholder="请选择考试"
            clearable
            :loading="loading"
          >
            <el-option
              v-for="exam in examList"
              :key="exam.examId"
              :label="exam.title"
              :value="exam.examId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">分析</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 统计卡片 -->
      <div class="stat-cards">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <template #header>
                <div class="stat-header">
                  <span>参考人数</span>
                  <el-icon><User /></el-icon>
                </div>
              </template>
              <div class="stat-value">{{ statistics.totalStudents }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <template #header>
                <div class="stat-header">
                  <span>平均分</span>
                  <el-icon><DataLine /></el-icon>
                </div>
              </template>
              <div class="stat-value">{{ statistics.averageScore }}分</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <template #header>
                <div class="stat-header">
                  <span>及格率</span>
                  <el-icon><PieChart /></el-icon>
                </div>
              </template>
              <div class="stat-value">{{ statistics.passRate.toFixed(1) }}%</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <template #header>
                <div class="stat-header">
                  <span>作弊率</span>
                  <el-icon><Warning /></el-icon>
                </div>
              </template>
              <div class="stat-value">{{ statistics.cheatingRate.toFixed(1) }}%</div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 图表区域 -->
      <div class="charts">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <span>成绩分布</span>
                </div>
              </template>
              <div class="chart-container">
                <div ref="scoreDistributionChart" style="width: 100%; height: 300px"></div>
                <el-table :data="scoreDistribution" border style="margin-top: 16px">
                  <el-table-column prop="scoreRange" label="分数区间" />
                  <el-table-column prop="count" label="人数" />
                </el-table>
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <span>题目正确率</span>
                </div>
              </template>
              <div class="question-accuracy-list scrollable-list">
                <el-row :gutter="16">
                  <el-col :span="24" v-for="item in questionAccuracy" :key="item.questionId" style="margin-bottom: 12px;">
                    <el-card shadow="never" class="question-accuracy-item">
                      <div class="qa-content">
                        <div class="qa-title">{{ item.questionContent }}</div>
                        <el-progress
                          :percentage="item.accuracy.toFixed(1)"
                          :color="item.accuracy >= 80 ? '#67C23A' : item.accuracy >= 60 ? '#E6A23C' : '#F56C6C'"
                          :stroke-width="18"
                          style="width: 60%; margin: 0 16px;"
                          show-text
                        />
                      </div>
                    </el-card>
                  </el-col>
                </el-row>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 作弊分析 -->
      <div class="cheating-analysis">
        <el-card>
          <template #header>
            <div class="chart-header">
              <span>作弊分析</span>
            </div>
          </template>
          <el-table :data="cheatingAnalysis" border style="width: 100%">
            <el-table-column prop="eventType" label="作弊类型" width="150" />
            <el-table-column prop="count" label="发生次数" width="100" />
            <el-table-column prop="percentage" label="占比" width="100">
              <template #default="{ row }">
                {{ row.percentage.toFixed(1) }}%
              </template>
            </el-table-column>
            <el-table-column prop="description" label="说明" />
          </el-table>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { User, DataLine, PieChart, Warning } from '@element-plus/icons-vue'
import { getGradeAnalysis, getExamList } from '@/api/exam' // 引入API
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'

interface Exam {
  exam_id: number
  title: string
}

const router = useRouter()

// 搜索表单
const searchForm = reactive({
  examId: ''
})

// 考试列表
const examList = ref<Exam[]>([])
const loading = ref(false)

// 获取考试列表
const fetchExamList = async () => {
  try {
    loading.value = true
    const res = await getExamList()
    if (res.code === 200) {
      examList.value = res.data.records
      console.log(examList.value)
    } else {
      ElMessage.error(res.data.msg || '获取考试列表失败')
    }
  } catch (error) {
    console.error('获取考试列表失败:', error)
    ElMessage.error('获取考试列表失败')
  } finally {
    loading.value = false
  }
}

// 统计数据
const statistics = reactive({
  totalStudents: 0,
  averageScore: 0,
  passRate: 0,
  cheatingRate: 0
})

const scoreDistribution = ref<any[]>([])
const questionAccuracy = ref<any[]>([])
const cheatingAnalysis = ref<any[]>([])

const scoreDistributionChart = ref()
const questionAccuracyChart = ref()

function renderScoreDistChart() {
  if (!scoreDistributionChart.value) return
  const chart = echarts.init(scoreDistributionChart.value)
  const data = scoreDistribution.value
  chart.setOption({
    title: { text: '成绩分布', left: 'center' },
    tooltip: {},
    xAxis: {
      type: 'category',
      data: data.map(i => i.scoreRange)
    },
    yAxis: { type: 'value' },
    series: [{
      type: 'bar',
      data: data.map(i => i.count),
      itemStyle: { color: '#409EFF' }
    }]
  })
}

function renderQuestionAccChart() {
  if (!questionAccuracyChart.value) return
  const chart = echarts.init(questionAccuracyChart.value)
  const data = questionAccuracy.value
  chart.setOption({
    title: { text: '题目正确率', left: 'center' },
    tooltip: {},
    xAxis: {
      type: 'category',
      data: data.map(i => i.questionContent)
    },
    yAxis: { type: 'value', min: 0, max: 100 },
    series: [{
      type: 'bar',
      data: data.map(i => i.accuracy),
      itemStyle: { color: '#67C23A' }
    }]
  })
}

// 搜索
const handleSearch = async () => {
  if (!searchForm.examId) return
  const res = await getGradeAnalysis(Number(searchForm.examId))
  const data = res.data.data
  statistics.totalStudents = data.totalStudents
  statistics.averageScore = data.averageScore
  statistics.passRate = data.passRate
  statistics.cheatingRate = data.cheatingRate
  scoreDistribution.value = data.scoreDistribution || []
  questionAccuracy.value = data.questionAccuracy || []
  cheatingAnalysis.value = data.cheatingAnalysis || []
  renderScoreDistChart()
  renderQuestionAccChart()
}

// 重置
const handleReset = () => {
  searchForm.examId = ''
  statistics.totalStudents = 0
  statistics.averageScore = 0
  statistics.passRate = 0
  statistics.cheatingRate = 0
  scoreDistribution.value = []
  questionAccuracy.value = []
  cheatingAnalysis.value = []
  handleSearch()
}

// 返回
const handleBack = () => {
  router.back()
}

// 初始化
onMounted(async () => {
  await fetchExamList()
})
</script>

<style scoped>
.grade-analysis {
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
  overflow-y: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 100%;
}

.stat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  text-align: center;
  margin-top: 10px;
}

.charts {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  font-weight: 500;
}

.chart-container {
  height: 300px;
}

.cheating-analysis {
  margin-top: 20px;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-table) {
  margin-bottom: 20px;
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto;
  max-height: 400px;
}

:deep(.el-row) {
  margin-bottom: 20px;
}

:deep(.el-col) {
  margin-bottom: 20px;
}

@media screen and (max-width: 768px) {
  .stat-cards :deep(.el-col) {
    width: 100%;
  }

  .charts :deep(.el-col) {
    width: 100%;
  }
}

:deep(.el-select),
:deep(.el-form-item__content) {
  min-width: 200px;
}
:deep(.el-select-dropdown) {
  min-width: 220px !important;
}
:deep(.el-select-dropdown__item) {
  white-space: normal;
  word-break: break-all;
  min-width: 200px;
}

.question-accuracy-list {
  margin-top: 16px;
  max-height: 350px;
  overflow-y: auto;
  padding-right: 8px;
}
.question-accuracy-item {
  padding: 12px 16px;
  background: #f9f9f9;
}
.qa-content {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}
.qa-title {
  flex: 1;
  font-weight: 500;
  color: #303133;
  white-space: normal;
  word-break: break-all;
  margin-right: 12px;
  font-size: 15px;
  line-height: 1.5;
}
</style>
